<template>
  <div class="content">
    <div class="mainView">
      <div class="main">
          <div class="data" v-if="nowIndex == 1">
            <el-form :model="firstForm" :rules="firstRules" ref="firstForm" label-width="0px" >
              <el-form-item prop="bitChecked">
                <div class="label">选择币种</div>
                <el-select
                  class="select"
                  v-model="firstForm.bitChecked"
                  @change="listenBitChange"
                  placeholder="请选择币种">
                  <span slot="prefix" v-if="firstForm.bitChecked" class="prefixLeft">
                    <i class="iconfont logoicon icon-eos"></i>
                  </span>
                  <div slot="prefix" v-if="firstForm.bitChecked" class="prefixRight">
                    可用: <span>{{firstForm.usableCount}}</span>
                  </div>
                  <el-option
                    v-for="item in firstForm.bit"
                    :key="item.name"
                    :label="item.code"
                    :value="item.code">
                    <span style="float: left">{{ item.code }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.usableCount }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item prop="oldCount" class="hidden">
                <div class="label">收款方EOS账户名</div>
                <el-select placeholder="请选择" class="select" v-model="firstForm.oldCount" @change="listenNewPerson">
                  <el-option
                    v-for="(item,$index) in firstForm.oldCountList"
                    :key="item.payee"
                    :label="`${item.payee} - ${item.remark}`"
                    :value="item.payee + '/' + item.remark">
                    <span style="float: left">{{ item.payee + ' - ' + item.remark }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px" @click.stop="handleDelectOld($index)">X</span>
                  </el-option>
                  <el-option
                  label="新增账户"
                  value="add">
                    <div> + 新增账户</div>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="newCount" v-if="firstForm.showNewPerson" style="margin-top: -10px">
                <div class="newPerson flex newAccount">
                  <el-input placeholder="请输入对方EOS账户名" v-model="firstForm.newCount" style="width: 350px"></el-input>
                  <span class="line"> - </span>
                  <el-input placeholder="昵称,便于记忆"  v-model="firstForm.newNick" class="nick"></el-input>
                </div>
              </el-form-item> -->
              <el-form-item>
                <div class="label">收款方EOS账户名</div>
                <el-input placeholder="请输入收款方EOS账户名" v-model="firstForm.toAccount">
                </el-input>
              </el-form-item>
              <div class="warn"><span class="iconfont logoicon icon-shuoming warn-icon"></span> 务必提供正确的EOS账户名,否则将无法找回资产</div>
              <el-form-item prop="transfersNum">
                <div class="label">转账数量</div>
                <el-input type="number" placeholder="请输入转账数量" v-model="firstForm.transfersNum">
                  <template slot="append">{{firstForm.bitIcon ? firstForm.bitIcon : 'EOS'}}</template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <div class="label">留言(选填,对方可见)</div>
                <el-input placeholder="请输入留言内容" v-model="firstForm.message">
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :loading="loading" class="btn" @click="handleSubmitForm('firstForm')">提交转账</el-button>
              </el-form-item>
            </el-form>
          </div>

          <div class="count-2" v-if="nowIndex == 2">
            <div class="transferInfo">
              <el-row :gutter="20">
                <el-col :span="8" :offset="5">
                  <span class="count-2-label">币种:</span>
                  <span class=""><i class=""></i>{{firstForm.bitIcon}}</span>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="7" :offset="5">
                  <span class="count-2-label">收款方EOS账户名:</span>
                  <span class="">{{ firstForm.newCount }}({{ firstForm.newNick }})</span>
                </el-col>
                <el-col :span="8" :offset="2">
                  <span class="count-2-label">转账数量:</span>
                  <span class="count-2-transCount">{{ firstForm.transfersNum }} {{firstForm.bitIcon}}</span>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="7" :offset="5">
                  <span class="count-2-label">留言:</span>
                  <span class="">{{ firstForm.message }}</span>
                </el-col>
                <el-col :span="8" :offset="2">
                  <span class="count-2-label">转账手续费:</span>
                  <span class="">免费</span>
                </el-col>
              </el-row>
            </div>
            <div class="pwdDiv">
              <el-form :model="lastForm" :rules="lastRules" ref="lastForm" label-width="0px" >
                <el-form-item prop="pwd">
                  <div class="label">钱包密码</div>
                    <el-input type="password" placeholder="请输入钱包密码" v-model="lastForm.pwd">
                    </el-input>
                  </el-form-item>
                  <el-form-item>
                    <div><el-button type="primary" class="btn" @click="handleToNext">确认转账</el-button></div>
                    <el-button type="primary" plain class="btn" @click="handleBack">上一步</el-button>
                  </el-form-item>
              </el-form>
            </div>
          </div>

          <div class="count-3" v-if="nowIndex == 3">
            <div class="success">
              <img src="../../assets/img/wallet/trans-success.png" alt="">
              <div class="successTip">转账成功</div>
              <a href="javascript:;" class="toTransDetail">查看转账记录</a>
            </div>
          </div>

          <div class="tipOut">
            <div class="tip">
              <div class="tipTop"><span></span>温馨提示</div>
              <div class="tipContent">1.您转账的是EOS主链上发行的Token(代币),务必提供正确的EOS账户名</div>
              <div class="tipContent">2.如您提供的EOS账户名有误,将无法找回资产</div>
            </div>
          </div>
      </div>
    </div>
  </div>
</template>

<script>

import { EosModel } from '@/utils/eos/index';
import { validateEosName, toFixed } from '@/utils/validate';
import VerifyDeal from '@/components/VerifyDeal';

export default {
  components: {
    VerifyDeal
  },
  data() {
    // EOS账户名规则
    const eosNameVali = (rule, value, callback) => {
      if (!validateEosName(value)) {
        callback(new Error('EOS账户必须是字母+数字（1~5之间），且长度必须为12位'));
      } else {
        callback();
      }
    };
    const countReg = (rule, value, callback) => {
      const reg = new RegExp(/^\d+(\.\d{0,4})?$/);
      if (!reg.test(value) || value <= 0) {
        callback(new Error('转账数量必须大于0的数字,且小数点后不大于4位'));
      } else {
        callback();
      }
    };
    return {
      nowIndex: 1, // 当前处于转账第几步
      verifyDealVisible: false, // 验证信息是否显示
      loading: false,
      /* 转账第一步信息 */
      firstForm: {
        bit: [], // 用户所有币种列表
        coinId: null, // 选中币种的ID
        bitChecked: 'EOS', // 币种选择
        bitIcon: '', // 币种图标
        usableCount: 0, // 币种可用余额
        contract: '', // 币种合約

        oldCountList: [], // 历史联系人列表
        oldCount: '', // 选中的历史联系人信息
        showNewPerson: false, // 新增联系人
        newCount: '', // 新增联系人账号
        newNick: '', // 新增联系人昵称
        toAccount: '', // 收款方EOS账户名
        transfersNum: '', // 转账数量
        message: '', // 留言(选填)
      },
      firstRules: { // 第一步表单验证
        bitChecked: [
          { required: true, message: '请选择币种', trigger: 'change' }
        ],
        oldCount: [
          { required: true, message: '请选择联系人', trigger: 'change' }
        ],
        newCount: [
          { required: true, message: '请输入对方EOS账户', trigger: 'blur' },
          { validator: eosNameVali, trigger: 'blur' }
        ],
        transfersNum: [
          { required: true, message: '请输入转账数量', trigger: 'blur' },
          { validator: countReg, trigger: 'blur' }
        ]
      },

      /* 第二步 验证密码 */
      reg: {
        mailEnable: false,
        phoneEnable: false,
        authenticatorEnable: false,
        flag: true
      }, // 安全验证信息
      sendCode: false, // 是否禁用发送手机验证码
      countDown: 60, // 默认60s后允许再次发送手机验证码
      timer: null, // 手机验证码定时器
      sendCodeEmail: false, // 是否禁用发送邮箱验证码
      countDownEmail: 60, // 默认60s后允许再次发送邮箱验证码
      timerEmail: null, // 邮箱验证码定时器
      lastForm: {
        pwd: '', // 钱包密码
        validator: '', // 验证器验证码
        phone: '', // 手机验证码
        email: '', // 邮箱验证码
        flag: false, // 组件验证器是否传值回来
      },
      lastRules: {
        pwd: [
          { required: true, message: '请输入钱包密码', trigger: 'change' }
        ],
        validator: [
          { required: true, message: '请输入验证器验证码', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入手机验证码', trigger: 'change' }
        ],
        email: [
          { required: true, message: '请输入邮箱验证码', trigger: 'change' }
        ],
      }
    };
  },
  props: {
    coinInfoList: {
      type: Array,
      defalut: [],
    },
    totalResources: {
      type: Object,
      default: null,
    },
    eosBalance: {
      type: String,
      default: '0.0000 EOS'
    },
    symbolScience: {
      type: String,
      default: 'EOS'
    },
  },
  watch: {
    coinInfoList: function change() {
      this.firstForm.bit = this.coinInfoList;
      this.listenBitChange(this.firstForm.bitChecked);
    },
  },
  created() {
  },
  mounted() {
    this.firstForm.bit = this.coinInfoList;
    const app = this.$store.state.app;
    const xc = app.exchangeAccount;
    const chain = app.scatter.chain;
    this.firstForm.toAccount = xc[chain];
    this.firstForm.bitIcon = chain.toUpperCase();
    this.firstForm.bitChecked = chain.toUpperCase();
  },
  methods: {
    // 提交转账时验证必填信息
    handleSubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.loading = true;
        // this.handleSavePayee();
        // this.handleToNext();
        this.handleTransAction();
        return true;
      });
    },
    // 開始轉賬
    handleTransAction() {
      const params = {
        code: this.firstForm.contract,
        toAccount: this.firstForm.toAccount,
        quantity: `${toFixed(this.firstForm.transfersNum, 4)} ${this.firstForm.bitChecked}`,
        remarks: this.firstForm.message,
      }
      const scat = this.$store.state.app.scatter;
      // 其他钱包下单
      if (scat.wallet !== 'Scatter'
      && scat.wallet !== 'Ironman'
      && scat.wallet !== 'cloudWallet') {
        this.$message.error('非Scatter錢包');
        this.loading = false;
        // this.handleOrderByWallet(params);
        return;
      }
      // Scatter 下单
      EosModel.eosTransaction(params, (res) => {
        this.loading = false;
        if (res.processed) { // 买入RAM成功
          this.$emit('listenToCoinList', 'refresh');
          this.$message.success('轉賬成功！');
          return
        }
        EosModel.handleScatterErrorBack(res);
      });
    },
    // 其他钱包下单
    handleOrderByWallet() {

    },
    // 转账数量 - 保留4位小数
    handleTransNum() {
    },
    /* 币种操作 start */
    handleUserCoinList() { // 获取用户下所有币种
      this.$http.post('/userCoin/list').then((res) => {
        this.firstForm.bit = res.userCoinList;
      });
    },
    listenBitChange(val) { // 币种选择-change事件-改变图标和可用余额
      const item = this.coinInfoList.find(v => v.code === val);
      this.firstForm.bitChecked = item.code;
      this.firstForm.bitIcon = item.code;
      this.firstForm.contract = item.contract;
      this.firstForm.coinId = item.coinId;
      this.firstForm.usableCount = item.usableCount;
    },
    /* 币种操作 end */

    /* 联系人操作 start */
    handleGetUserpPayeeList() { // 获取历史联系人列表
      this.$http.post('/userPayee/list').then((res) => {
        this.firstForm.oldCountList = res.payeeList;
      });
    },
    handleDelectOld(index) { // 删除旧联系人
      const params = {
        payeeId: this.firstForm.oldCountList[index].id,
      };
      this.$http.post('/userPayee/delete', params).then((res) => {
        if (res.code === 0) {
          this.firstForm.oldCountList.splice(index, 1);
          this.$message.success('联系人删除成功');
        } else {
          this.$message.error('联系人删除失败');
        }
      });
    },
    listenNewPerson(item) { // 显示新增联系人输入信息
      if (this.firstForm.oldCount === 'add') {
        this.firstForm.showNewPerson = true;
        this.firstForm.newNick = '';
        this.firstForm.newCount = '';
      } else {
        this.firstForm.showNewPerson = false;
        this.firstForm.newNick = item.split('/')[1];
        this.firstForm.newCount = item.split('/')[0];
      }
    },
    handleSavePayee() { // 保存联系人信息
      if (this.firstForm.showNewPerson) {
        const params = {
          payee: this.firstForm.newCount,
          remark: this.firstForm.newNick,
        };
        this.$http.post('/userPayee/save', params).then((res) => {
          if (res.code === 0) {
            this.$message.success('联系人保存成功');
          } else {
            this.$message.error('联系人保存失败');
          }
        });
      }
    },
    /* 联系人操作 end */

    /* 按钮操作 start */
    handleToNext() { // 提交转账
      if (this.nowIndex === 1) {
        // if (window.parseInt(this.firstForm.usableCount) < window.parseInt(this.firstForm.transfersNum)) {
        //   this.$message.error('转账数量不能大于可用余额');
        //   return;
        // }
        this.nowIndex = 2;
      } else {
        this.handleSureTransfer();
      }
    },
    handleBack() { // 上一步
      this.nowIndex = 1;
    },
    /* 其他操作 start */
    handleSureTransfer() { // 确认转账
      // const params = {
      //   code: '',
      //   toAccount: this.firstForm.newCount,
      //   quantity: this.firstForm.transfersNum,
      //   memo: this.firstForm.message,
      // }
      // console.log(params);

      // if (!this.lastForm.pwd) {
      //   this.$message.error('请输入钱包密码');
      //   return;
      // }
      // const params = {
      //   coinId: this.firstForm.coinId,
      //   coinCode: this.firstForm.bitIcon,
      //   payee: this.firstForm.newCount,
      //   count: this.firstForm.transfersNum,
      //   memo: this.firstForm.message,
      //   walletPassword: this.lastForm.pwd,
      //   authenticatorCode: this.lastForm.validator,
      //   smsVerifyCode: this.lastForm.phone,
      //   emailVerifyCode: this.lastForm.email,
      // };
      // this.$http.post('/userCoin/transfer', params).then((res) => {
      //   if (res.code === 0) {
      //     this.nowIndex = 3;
      //   } else {
      //     this.$message.error(res.msg);
      //   }
      // });
    },
    /* 其他操作 end */
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/variables.scss';

.content{
  padding-bottom: 20px;
  min-height: 950px;

  .mainView{
    color: black;
    width: $-min-width;
    margin: auto;

    .topUrl{
      padding: 18px 0px;

      a{
        font-weight: bold;
        margin: 8px 15px 8px 20px;
      }
    }

    .main{
      background-color: #fff;
      min-height: 500px;
      position: relative;
      padding-top: 28px;
      padding-bottom: 188px;

      .select{
        width: 100%;
      }

      /deep/ .el-input__prefix{
        width: 90%;
        line-height: 40px;
      }

      .prefixLeft{
        float: left;
        margin-left: 5px;
      }

      .prefixRight{
        float: right;
      }

      .newPerson{
        margin-top: 10px;

        /deep/ .el-input{
          margin: 0;
        }

        .newAccount{
          display: inline-block;
          width: 60%;
        }

        .nick{
          width: 29%;
        }

        .line{
          text-align: center;
          display: inline-block;
          width: 8.2%;
        }
      }
    }

    .tip,
    .data{
      width: 500px;
      margin: auto;
      position: relative;
    }

    .data{
      /deep/ .el-form-item__content {
        margin-bottom: 15px;
      }

      /deep/ .el-form-item{
        margin-bottom: 0px;
      }

      .label{
        height: 35px;
        font-weight: bold;
        font-size: 16px;
        padding: 0;
      }

      .warn{
        padding: 0;
        color: #999;

        .warn-icon{
          color: #FEC576;
          border-radius: 50%;
        }
      }

      .btn{
        margin: 20px 0px;
        width: 100%;
      }
    }

    .count-2{
      padding: 20px 0px;

      .transferInfo{
        margin: 20px;
        padding: 0px 0px 20px 0px;
        border-bottom: 1px solid rgba(0,0,0,.2);

        .count-2-label{
          color: gray;
          line-height: 40px;
        }

        .count-2-transCount{
          color: #3F99DC;
        }
      }

      .pwdDiv{
        width: 500px;
        margin: auto;
        position: relative;

        .label{
          font-size: 16px;
          padding: 15px 0px 0px 0px;
        }

        .btn{
          margin-top: 15px;
          width: 100%;
          display: block;
        }

        .codes{
          width: calc(100% - 118px);
        }

        .sendCodes{
          width: 112px;
        }
      }
    }

    .count-3{
      height: 100%;
      position: relative;
      text-align: center;
      padding-top: 100px;

      .successTip{
        font-size: 20px;
        padding: 8px 0px 25px 0px;
      }

      .toTransDetail{
        font-size: 14px;
        color: #3F99DC;
      }
    }

    .tipOut{
      padding-top: 20px;
      background: #F5FAFE;
      width: 100%;
      position: absolute;
      bottom: 0px;

      .tip{
        padding: 30px 0px;

        .tipTop{
          color: #3F99DC;
          padding: 10px 0px;
        }

        .tipContent{
          padding: 2px 0px;
          color: gray;
        }
      }
    }
  }
}
.theme-1B1D27{
  .content{
    .mainView{
      .topUrl{
        /deep/ .el-breadcrumb__inner{
          color: rgba(255,255,255,0.8);
        }
      }
      .main{
        color: rgba(255,255,255,0.8);
        background: #181b2a;

        .tipOut{
          background: rgba(0, 0, 0, .4)
        }
      }
    }
  }
}
</style>
